<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ssh:config:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ssh:config:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="configList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="用户名" align="center" prop="user.userName" />
      <el-table-column label="用户昵称" align="center" prop="user.nickName" />
      <el-table-column label="夜间模式" align="center" prop="nightMode">
        <template slot-scope="scope">
          <el-tag :type="scope.row.nightMode === 1 ? 'success' : 'info'">
            {{ scope.row.nightMode === 1 ? "开启" : "关闭" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="自动下一章" align="center" prop="autoNext">
        <template slot-scope="scope">
          <el-tag :type="scope.row.autoNext === 1 ? 'success' : 'info'">
            {{ scope.row.autoNext === 1 ? "开启" : "关闭" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="自动保存" align="center" prop="autoSave">
        <template slot-scope="scope">
          <el-tag :type="scope.row.autoSave === 1 ? 'success' : 'info'">
            {{ scope.row.autoSave === 1 ? "开启" : "关闭" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="字体大小(px)" align="center" prop="fontSize" />
      <el-table-column label="文本对齐方式" align="center" prop="textAlign" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ssh:config:edit']"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改用户设置对话框 -->
    <el-dialog
      title="修改用户设置"
      :visible.sync="updateOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="updateForm"
        :model="updateForm"
        :rules="updateRules"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="updateForm.userName" readonly />
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickName">
          <el-input v-model="updateForm.nickName" readonly />
        </el-form-item>
        <el-form-item label="夜间模式" prop="nightMode">
          <el-radio-group v-model="updateForm.nightMode">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="自动下一章" prop="autoNext">
          <el-radio-group v-model="updateForm.autoNext">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="自动保存" prop="autoSave">
          <el-radio-group v-model="updateForm.autoSave">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="字体大小(px)" prop="fontSize">
          <el-select
            v-model="updateForm.fontSize"
            placeholder="请选择字体大小"
            style="width: 100%"
          >
            <el-option :label="16" :value="16"></el-option>
            <el-option :label="18" :value="18"></el-option>
            <el-option :label="20" :value="20"></el-option>
            <el-option :label="22" :value="22"></el-option>
            <el-option :label="24" :value="24"></el-option>
            <el-option :label="26" :value="26"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文本对齐方式" prop="textAlign">
          <el-select
            v-model="updateForm.textAlign"
            placeholder="请选择对齐方式"
            style="width: 100%"
          >
            <el-option label="左对齐" value="左对齐"></el-option>
            <el-option label="居中" value="居中"></el-option>
            <el-option label="右对齐" value="右对齐"></el-option>
            <el-option label="智能" value="智能"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdateForm">确 定</el-button>
        <el-button @click="cancelUpdate">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConfig, getConfig, updateConfig } from "@/api/ssh/config";
import { listStudent, getStudent } from "@/api/youyou/student";

export default {
  name: "Config",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户设置表格数据
      configList: [],
      // 用户列表
      userList: [],
      // 修改弹出层标题
      updateOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        nickName: null,
      },
      // 修改表单参数
      updateForm: {
        id: null,
        userId: null,
        nightMode: 0,
        autoNext: 0,
        autoSave: 0,
        fontSize: 14,
        textAlign: "",
        userName: "",
        nickName: "",
      },
      // 修改表单校验
      updateRules: {
        nightMode: [
          { required: true, message: "夜间模式不能为空", trigger: "change" },
        ],
        autoNext: [
          { required: true, message: "自动下一章不能为空", trigger: "change" },
        ],
        autoSave: [
          { required: true, message: "自动保存不能为空", trigger: "change" },
        ],
        fontSize: [
          { required: true, message: "字体大小不能为空", trigger: "blur" },
        ],
        textAlign: [
          {
            required: true,
            message: "文本对齐方式不能为空",
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getUserList();
  },
  methods: {
    /** 查询用户设置列表 */
    getList() {
      this.loading = true;

      // 构建查询参数
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        user: {
          userName: this.queryParams.userName,
          nickName: this.queryParams.nickName,
        },
      };

      console.log("查询参数:", params);

      listConfig(params)
        .then((response) => {
          console.log("获取到的用户设置列表:", response.rows);
          this.configList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch((error) => {
          console.error("获取用户设置列表失败:", error);
          this.configList = [];
          this.total = 0;
          this.loading = false;
        });
    },
    /** 查询用户列表 */
    getUserList() {
      listStudent()
        .then((response) => {
          this.userList = response.rows;
        })
        .catch((error) => {
          console.error("获取用户列表失败:", error);
          this.userList = [];
        });
    },
    // 取消修改按钮
    cancelUpdate() {
      this.updateOpen = false;
      this.resetUpdateForm();
    },
    // 修改表单重置
    resetUpdateForm() {
      this.updateForm = {
        id: null,
        userId: null,
        nightMode: 0,
        autoNext: 0,
        autoSave: 0,
        fontSize: 14,
        textAlign: "",
        userName: "",
        nickName: "",
      };
      this.resetForm("updateForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetUpdateForm();
      const id = row.id || this.ids;
      getConfig(id)
        .then((response) => {
          this.updateForm = response.data;

          // 通过userId获取用户名和昵称
          if (this.updateForm.userId) {
            this.getUserInfo(this.updateForm.userId);
          }

          this.updateOpen = true;
        })
        .catch((error) => {
          console.error("获取用户设置详情失败:", error);
          this.$modal.msgError("获取用户设置详情失败");
        });
    },

    /** 根据用户ID获取用户信息 */
    getUserInfo(userId) {
      // 从已有的用户列表中查找
      const user = this.userList.find((u) => u.userId === userId);
      if (user) {
        this.updateForm.userName = user.userName;
        this.updateForm.nickName = user.nickName;
      } else {
        // 如果用户列表中找不到，则通过API获取
        getStudent(userId)
          .then((response) => {
            const userInfo = response.data;
            this.updateForm.userName = userInfo.userName;
            this.updateForm.nickName = userInfo.nickName;
          })
          .catch((error) => {
            console.error("获取用户信息失败:", error);
            this.updateForm.userName = "未知用户";
            this.updateForm.nickName = "未知昵称";
          });
      }
    },
    /** 提交修改表单 */
    submitUpdateForm() {
      this.$refs["updateForm"].validate((valid) => {
        if (valid) {
          updateConfig(this.updateForm).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.updateOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "ssh/config/export",
        this.queryParams,
        `config_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
